# -*- coding: utf-8 -*-
# @Time    : 2022/11/1 16:53
# @Author  : yangyuexiong
# @Email   : yang6333yyx@126.com
# @File    : __init__.py.py
# @Software: PyCharm

import os

# os.environ.update({"__COMPAT_LAYER": "RUnAsInvoker"})

"""
lackey可能会引起pyinstaller打包后的exe程序启动后出现键盘与鼠标出现失灵的现象！
"""
import time

import shortuuid
# import lackey
from pywinauto import Application, findwindows
from pywinauto.keyboard import send_keys
from openpyxl import load_workbook

from common.libs.func import get_pid

dlg_dict = {
    "主窗口": {
        "title": "微信",
        "class_name": "WeChatMainWndForPC"
    },
    "通讯录管理窗口": {
        "title": "通讯录管理",
        "class_name": "ContactManagerWindow"
    },
}


class WeChatAuto:
    """微信"""

    def __init__(self, path):

        self.app = Application(backend='uia').start(path)
        if not self.app.windows():
            self.app = Application(backend='uia').connect(path=path)

        self.main_dlg = None
        self.init_dlg = self.gen_dlg(**dlg_dict['主窗口'])

        # self.main_dlg.print_control_identifiers()

    def gen_dlg(self, **kwargs):
        """切换当前窗口"""

        print(kwargs)
        title = kwargs.get('title')
        class_name = kwargs.get('class_name')
        dlg_handles = findwindows.find_windows(title=title, class_name=class_name)
        print(dlg_handles)
        if dlg_handles:
            self.main_dlg = self.app.window_(handle=dlg_handles[0])
            self.main_dlg.wait('ready', timeout=10)
            return self.main_dlg
        else:
            raise IndexError(f'获取{title}窗口失败')

    def windows_reset(self):
        """窗口位置居左上角平行"""

        self.main_dlg.move_window(0, 0)

    def lt(self):
        """聊天"""

        self.main_dlg.child_window(title="聊天", control_type="Button").click_input()

    def txl(self):
        """通讯录"""

        self.main_dlg.child_window(title="通讯录", control_type="Button").click_input()

    def sc(self):
        """收藏"""

        self.main_dlg.child_window(title="收藏", control_type="Button").click_input()

    def pyq(self):
        """朋友圈"""

        self.main_dlg.child_window(title="朋友圈", control_type="Button").click_input()

    def click_search(self):
        """点击搜搜"""

        try:
            self.main_dlg.child_window(title="搜索", control_type="Edit").click_input()  # 控件识别
        except BaseException as e:
            print(e)
            # lackey.click('.\\png\\wx_search.png')  # 图片识别

    def input(self, name):
        """输入"""

        try:
            send_keys(name)  # 控件识别
        except BaseException as e:
            print(e)
            # lackey.type(name)  # 图片识别

    def send_btn(self):
        """发送按钮"""

        try:
            self.main_dlg.child_window(title="sendBtn", control_type="Button").click_input()  # 控件识别
        except BaseException as e:
            print(e)
            # lackey.click('.\\png\\send.png')  # 图片识别

    def close(self):
        """收起"""

        send_keys('{ESC}')

    def gen_sheet(self, excel_path):
        """
        获取：excel sheet
        :param excel_path:  excel.xlsx文件路径
        :return:
        """

        try:
            wb = load_workbook(excel_path)
            print(wb)
            sheet_list = wb.sheetnames
            print(sheet_list)
            sheet = wb[sheet_list[0]]
            return sheet
        except BaseException as e:
            print(f'打开excel文件失败:{e}')
            return False

    def gen_send_user_list(self, sheet_obj):
        """
        生成发送消息用户对象列表
        :param sheet_obj: sheet对象
        :return:
        """

        user_list = []
        for i in range(2, sheet_obj.max_row + 1):
            wx_code = sheet_obj.cell(i, 1).value
            message = sheet_obj.cell(i, 2).value
            if wx_code and message:
                d = {"wx_code": wx_code, "message": message, "uuid": shortuuid.uuid()}
                user_list.append(d)

        return user_list

    def gen_edit_pyq_auth_user_list(self, sheet_obj):
        """
        生成修改朋友圈权限用户对象列表
        :param sheet_obj: sheet对象
        :return:
        """

        user_list = []
        for i in range(2, sheet_obj.max_row + 1):
            wx_name = sheet_obj.cell(i, 1).value
            wx_code = sheet_obj.cell(i, 2).value
            dont_let_it = sheet_obj.cell(i, 3).value
            dont_look = sheet_obj.cell(i, 4).value
            if wx_name and wx_code:
                d = {
                    "wx_name": wx_name,
                    "wx_code": wx_code,
                    "dont_let_it": dont_let_it,
                    "dont_look": dont_look,
                    "uuid": shortuuid.uuid()
                }
                user_list.append(d)

        return user_list

    def wx_send_message(self, user_list=None, is_excel=False, excel_path=None):
        """
        发送消息
        :param user_list: {"wx_code":"xxx","message":"你好呀"}
        :param is_excel: excel.xlsx
        :param excel_path: excel.xlsx文件路径
        :return:
        """

        if is_excel and excel_path:
            sheet_obj = self.gen_sheet(excel_path)
            user_list = self.gen_send_user_list(sheet_obj=sheet_obj)

        if not user_list:
            return None

        self.txl()

        for user in user_list:
            print(user)
            wx_code = user.get('wx_code')
            message = user.get('message')
            self.click_search()
            self.input(wx_code)
            time.sleep(1)
            send_keys("{ENTER}")
            self.main_dlg.child_window(title="输入", control_type="Edit").click_input()
            self.input(message)
            time.sleep(1)
            self.send_btn()

        self.close()

    def wx_edit_pyq_auth(self, user_list=None, is_excel=False, excel_path=None):
        """
        修改好友朋友圈权限
        :param user_list: {"wx_name": "Y.", "wx_code": "YangYuExionGaini72", "dont_look": True, "dont_let_it": True}
        :param is_excel: excel.xlsx
        :param excel_path: excel.xlsx文件路径
        :return:
        """

        if is_excel and excel_path:
            sheet_obj = self.gen_sheet(excel_path)
            user_list = self.gen_edit_pyq_auth_user_list(sheet_obj=sheet_obj)

        if not user_list:
            return None

        self.txl()
        self.main_dlg.child_window(title="通讯录管理", control_type="Button").click_input()
        self.gen_dlg(**dlg_dict['通讯录管理窗口'])

        for user in user_list:
            print(user)
            wx_name = user.get('wx_name')
            wx_code = user.get('wx_code')
            dont_let_it = user.get('dont_let_it')
            dont_look = user.get('dont_look')
            self.click_search()
            self.input(wx_code)
            time.sleep(1)

            try:
                self.main_dlg.child_window(title=wx_name, control_type="Text").click_input()  # 选中
                self.main_dlg.child_window(title="修改权限", control_type="Button").click_input()  # 修改权限

                CheckBox1 = self.main_dlg.child_window(found_index=2, control_type="CheckBox")
                CheckBox2 = self.main_dlg.child_window(found_index=3, control_type="CheckBox")

                """
                1,1：不修改
                0,0：全改
                0,1：改1不改2
                1,0：改2不改1
                """
                if dont_let_it == CheckBox1.get_toggle_state() and dont_look == CheckBox2.get_toggle_state():
                    self.main_dlg.child_window(title="取消", control_type="Button").click_input()
                elif dont_let_it != CheckBox1.get_toggle_state() and dont_look != CheckBox2.get_toggle_state():
                    CheckBox1.click_input()
                    CheckBox2.click_input()
                    self.main_dlg.child_window(title="确定", control_type="Button").click_input()
                elif dont_let_it != CheckBox1.get_toggle_state() and dont_look == CheckBox2.get_toggle_state():
                    CheckBox1.click_input()
                    self.main_dlg.child_window(title="确定", control_type="Button").click_input()
                else:
                    CheckBox2.click_input()
                    self.main_dlg.child_window(title="确定", control_type="Button").click_input()

                self.click_search()  # 获取焦点
                self.main_dlg.child_window(title="清空", control_type="Button").click_input()  # 点击 x
            except:
                print(f'微信好友：{wx_code} 不存在')
                self.click_search()  # 获取焦点
                self.main_dlg.child_window(title="清空", control_type="Button").click_input()  # 点击 x
                continue

        self.main_dlg.child_window(title="关闭", control_type="Button").click_input()
        self.close()


if __name__ == '__main__':
    wx_path = "C:\soft\other\WeChat\WeChat.exe"
    wx_pid = get_pid(name='WeChat.exe')

    wx_auto = WeChatAuto(path=wx_path)


    def test_send_send_message_json():
        """测试直接传参发送消息"""

        user_list1 = [
            {"wx_code": "YYx_33", "message": "你好呀 123"},
            {"wx_code": "YangYuExionGaini72", "message": "你好呀 456"}
        ]

        wx_auto.wx_send_message(user_list=user_list1)


    def test_send_send_message_excel():
        """测试通过excel模板获取数据发送消息"""

        wx_auto.wx_send_message(is_excel=True, excel_path='../../../t1.xlsx')


    def test_edit_pyq_auth_json():
        """测试直接传参修改好友朋友圈权限"""

        user_list2 = [
            {"wx_name": "Y.", "wx_code": "YangYuExionGaini7299999", "dont_look": True, "dont_let_it": True},
            {"wx_name": "Y.", "wx_code": "YangYuExionGaini72", "dont_look": True, "dont_let_it": True},
            {"wx_name": "Y.", "wx_code": "YangYuExionGaini72", "dont_look": False, "dont_let_it": False},
            {"wx_name": "Y.", "wx_code": "YangYuExionGaini72", "dont_look": True, "dont_let_it": False},
            {"wx_name": "Y.", "wx_code": "YangYuExionGaini72", "dont_look": False, "dont_let_it": True},
            {"wx_name": "Y.", "wx_code": "YangYuExionGaini72", "dont_look": False, "dont_let_it": False}
        ]

        wx_auto.wx_edit_pyq_auth(user_list=user_list2)


    def test_edit_pyq_auth_excel():
        """测试通过excel模板获取数据发送消息"""

        wx_auto.wx_edit_pyq_auth(is_excel=True, excel_path='../../../t2.xlsx')


    # test_send_send_message_json()
    # test_send_send_message_excel()

    # test_edit_pyq_auth_json()
    test_edit_pyq_auth_excel()
